<?php

/*
 * 
 * 微信扫一扫功能
 * 
 */
namespace M\Controller;
use Think\Controller;
class ScanController extends CommonController{
    
    
    /*
     * 扫一扫功能调用
     */
    
    public function index() {
        $this->display();
    }
    
    public function result() {
//        扫一扫的结果页面
        
        $barcode = I('get.barcode');
        $DB = M('product');
        $map['barcode']=$barcode;
        
        $res = $DB->where($map)->find();
        
        if(!empty($res))
        {
            /*
             * 有条码对应的数据的情况
             * 
             */
            //条码扫描次数+1
            $DB->where($map)->setInc('scan_count');
            
            
            $relative_foundings = $this->get_product_foundings($res);
            if(!empty($relative_foundings['ress']))
            {
                $res['item_count']= $relative_foundings['total_count'];
                $res['items']= ($relative_foundings['ress']);
            }
            else
            {
                $res['item_count']= 0;
                $res['items']=array();
            }
            
            $res['items']= ($relative_foundings['ress']);
            
            $more_data = $this->_get_tmp_data($res['classify_name']);
//            $this->json_output($res,"","",$more_data);
            $this->assign("result", $res);
            $this->assign("more_data", $more_data);
        }
        else
        {
            $more_data = $this->_get_tmp_data($res['classify_name']);
            $ress = $this->get_info_product_yiyuan($barcode);
            if(!empty($ress)){
               
                $this->assign("result", $ress);
                $this->assign("more_data", $more_data);
                
//                $this->json_output($ress,"","",$more_data);
            }
            else
            {
                
                
                $data=array();
//                $this->json_output($data,'ok','第三方API无输出',$more_data);
                
                $this->assign("result", $data);
                $this->assign("more_data", $more_data);
                
            }
            
        }
        
        
        $this->display();
    }
    /*
     * 程序自动批量计算
     */
    public function auto_calculate_product_matching() {
        if(IS_POST)
        {
            $id = I("post.id");
            $map['id']=  array('gt',$id);
            $products = M("product")->where($map)->field("id,barcode")->order("id")->limit(10)->select();
            
            if(!empty($products))
            {
                foreach ($products as $key => $value) {
                    
                    $lastid = $value['id'];
//                    print_r($value);
//                    $DB  = D("product");
                    $stamp_mark = $this->_auto_calculate_product_macthing_report($value['id']);
//                    if($stamp_mark)
//                    {
//
//                    }
//                    else
//                    {
//                        $DB->id = $products['id'];
//                        $DB->if_testreport = 0;
//                        $DB->save();
//                    }

                }
                
                $result['id']=$lastid;
                echo json_encode($result);
            
            }
            else
            {
                $result['id']=0;
                echo json_encode($result);
            }
            
            
        }
        else
        {
            $this->display();
        }
    }
    
    /*
     * 程序匹配只考虑 分类\品牌\品名这三个因素
     */
    public function _auto_calculate_product_macthing_report($pid) {
        $DB = M("product");
        $product = $DB->find($pid);
        
        //第一步考虑全名匹配
        $map1['product_name'] = $product['name'];
        $DB1 = M("third_party_product");
        $res1 = $DB1->where($map1)->select();
        
        if(!empty($res1))
        {
            foreach ($res1 as $key => $value) {
                
                $DB1->id = $value['id'];
                $DB1->barcode = $product['barcode'];
                $DB1->product_name_old = $product['name'];
                $DB1->save();
                
                $data['pid'] = $pid;
                $data['thirdid']=$value['id'];
                $data['ctime']=I("server.REQUEST_TIME");
                
                M("product_and_thirdparty_relationship")->add($data);
                
            }
            
//            print_r($res1);
            
            //标记为有数据
            $DB->id = $pid;
            $DB->if_testreport = 1;
            $DB->machine_match_count = count($res1);
            $DB->save();
            
            return TRUE;
        }
        else
        {
            //检查是否有 分类\品牌\品名 相同
            $map2['b_category'] = $product['classify_name'];
            $map2['brand'] =  $product['brand'];
            $map2['short_product_name'] = $product['shortname'];
            
            $res2 = $DB1->where($map2)->select();
            
            if(!empty($res2))
            {
                foreach ($res2 as $key => $value) {
                    $DB1->id = $value['id'];
                    $DB1->barcode = $product['barcode'];
                    $DB1->product_name_old = $product['name'];
                    $DB1->save();
                    
                    $data['pid'] = $pid;
                    $data['thirdid']=$value['id'];
                    $data['ctime']=I("server.REQUEST_TIME");

                    M("product_and_thirdparty_relationship")->add($data);
                
                }
                
                
                //标记为有数据
                $DB->id = $pid;
                $DB->if_testreport = 1;
                $DB->machine_match_count = count($res2);
                $DB->save();
                
//                print_r($res2);
                
                return TRUE;
            }
            else
            {
                $DB->id = $pid;
                $DB->if_testreport = 0;
                $DB->save();
                        
                return FALSE;
            }
            
            
            
        }
        
                
    }
    
    
    /*
     * 
     * 程序自动处理一下没有检测结果的数据,标记出来
     * 
     */
    
    public function chk_all_products_by_id() {
        $id = I("get.id");
        
        $map['id']=  array('gt',$id);
        
        $products = M("product")->where($map)->field("id,barcode")->order("id")->limit(1)->find();
        
        if(!empty($products))
        {
           $DB  = D("product");
        
        
            $stamp_mark = $this->result_chk_by_barcode($products['barcode']);
            
            if($stamp_mark)
            {
                //标记为有数据
                $DB->id = $products['id'];
                $DB->if_testreport = 1;
                $DB->save();
            }
            else
            {
                $DB->id = $products['id'];
                $DB->if_testreport = 0;
                $DB->save();
            }

            echo json_encode($products);
        }
        else
        {
            $result['id']=0;
            echo json_encode($result);
        }

    }
    
    
    public function chk_all_products() {
        
        $this->display();
    }
    
    public function result_chk_by_barcode($barcode) {
//        扫一扫的结果页面
        
//        $barcode = I('get.barcode');
        $DB = M('product');
        $map['barcode']=$barcode;
        
        $res = $DB->where($map)->find();
        
        if(!empty($res))
        {
            /*
             * 有条码对应的数据的情况
             * 
             */
            //条码扫描次数+1
//            $DB->where($map)->setInc('scan_count');
            
            
            $relative_foundings = $this->get_product_foundings($res);
            if(!empty($relative_foundings['ress']))
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
            

            
        }
        else
        {
            
            
        }
        
        
        $this->display();
    }
    
    
    
    /*
     * 找出该产品是否有对应的检测项目
     */
    
    private function get_product_foundings($product) {
        
        /*
         * 分成两部
         * 1. 找出现有的自身平台的报告
         * 2. 找出第三方的食药监数据匹配
         * 
         */
        $DB= M('fundings');
        
        $map['pid']=$product['id'];
        $res = $DB->where($map)->select();
        
        $res_thirdparty_data = $this->_get_thirdparty_report_data($product);
        $res_thirdparty = $res_thirdparty_data['res'];
        
//        print_r($res_thirdparty);
        if(empty($res))
        {
            $ress = $res_thirdparty;
            $total_count = $res_thirdparty_data['total_count'];
        }
        else
        {
            $ress = array_merge($res,$res_thirdparty);
            $total_count = $res_thirdparty_data['total_count']+count($res);
            
            
        }
        
        
        
        
//        print_r($ress);
        
        if(!empty($ress))
        {
            $data['ress']=$ress;
            $data['total_count']=$total_count;
        
            return $data;
        }
        else
        {
            $data['ress']=0;
            $data['total_count']=0;
            
            return $data;
        }
        
    }
    
    /*
     * 按照算法
     * http://note.youdao.com/share/web/file.html?id=f519bd39a7c320c6c5072c6a3e05a984&type=note
     * 匹配数据
     */
    
    private function _get_thirdparty_report_data($product) {
        $product_name = $product['name'];  //产品全称
        $product_shortname = $product['shortname'];//产品简称
        $classify_name = $product['classify_name']; // 分类名字
        $brand = $product['brand'];  //品牌名称
        $specification = $product['specification'];  //规格
        
        
        //        如果品牌和 分类都是空的，就返回空值数据
        if(empty($classify_name))
        {
            return array();
        }
        
        if(empty($brand) )
        {
            return array();
        }
        
        if(empty($classify_name)&&empty($brand))
        {
            return array();
        }
        
//        print_r($product);
        /*
         * 情况一：
         * 产品全称都能对应上
         * 
         */
        $DB = M("third_party_product");
        
        
//        $res1 = $DB->where(array('product_name'=>$product_name))->select();
        
        if(1==0)
        {
//            return $res1;
        }
        else
        {
            
            /*
             * 情况二：
             * 分类有
             * 品牌有
             * 
             * 匹配
             * 产品名称
             * 规格
             * 
             */
            $map2['b_category']=$classify_name;
            $map2['brand']=$brand;
            
            $map2['product_name'] = $product_name;
            $map2['product_model']=$specification;
            
            
            
            $res2 = $DB->where($map2)->limit(20)->field("id,product_name,batch_no,qualified,brand,product_model")->select();
            $res_total = $DB->where($map2)->count();
            
            if(!empty($res2))
            {
//                echo "1";
//                exit();
                
                $data['res'] = $res2;
                $data['total_count']=$res_total;
                return $data;
            }
            else
            {
                unset($map2['product_model']);
                $res2 = $DB->where($map2)->limit(20)->field("id,product_name,batch_no,qualified,brand,product_model")->select();
                
                $res_total = $DB->where($map2)->count();

                if(!empty($res2))
                {
//                    echo "2";
//                exit();
                
                    $data['res'] = $res2;
                    $data['total_count']=$res_total;
                    return $data;
                }
                
            }
            
            
            /*
             * 情况三
             * 
             * * 分类有
             * 品牌有
             * 
             * 匹配
             * 品名
             * 规格
             */
            $map3['b_category']=$classify_name;
            $map3['brand']=$brand;
            
            $map3['short_product_name']=$product_shortname;
            $map3['product_model']=$specification;
            
            $res3 = $DB->where($map3)->limit(20)->field("id,product_name,batch_no,qualified,brand,product_model")->select();
            
            $res_total = $DB->where($map3)->count();
            
            if(!empty($res3))
            {
                $data['res'] = $res3;
                $data['total_count']=$res_total;
//                echo "3";
//                exit();
                return $data;
            }
            else
            {
                unset($map3['product_model']);
                $res3 = $DB->where($map3)->limit(20)->field("id,product_name,batch_no,qualified,brand,product_model")->select();
                $res_total = $DB->where($map3)->count();
                if(!empty($res3))
                {
                    $data['res'] = $res3;
                     $data['total_count']=$res_total;
//                    echo "4";
//                exit();
                    return $data;
                }
                
            }
            
            /*
             * 情况四
             * 
             * 分类有
             * 品牌有
             * 
             * 匹配
             *  第三方库包含 条码品名
             * 规格
             * 
             */
            $map4['b_category']=$classify_name;
            $map4['brand']=$brand;
            
            if(!empty($product_shortname))
            {
                $map4['product_name']=array("like","%$product_shortname%");
                $map4['product_model']=$specification;
            }
            
            
            $res4 = $DB->where($map4)->limit(20)->field("id,product_name,batch_no,qualified,brand,product_model")->select();
//            echo $DB->getLastSql();
            $res_total = $DB->where($map4)->count();
            
            if(!empty($res4))
            {
                
                
                $data['res'] = $res4;
                $data['total_count']=$res_total;
                
//                echo "5";
//                exit();
                return $data;
            }
            else
            {
                unset($map4['product_model']);
//                unset($map4['product_name']);
                $res4 = $DB->where($map4)->limit(20)->field("id,product_name,batch_no,qualified,brand,product_model")->select();
//                echo $DB->getLastSql();
//                echo "<br/>";
//                print_r(($res4));
//                exit();
                
                $res_total = $DB->where($map4)->count();
                if(!empty($res4))
                {
                    $data['res'] = $res4;
                    $data['total_count']=$res_total;
                    
//                    echo "6";
//                exit();
                    return $data;
                }
            }
       
        }
        
        
        
    }
    
    
    /*
     * 临时获取 如何选购 和 常见问题，
     * 
     */
    public function _get_tmp_data($classify_name) {
        $res = M("food_classify")->where(array('name'=>$classify_name))->find();
        
        if(!empty($res))
        {
            $how_to_buy['title'] = $classify_name."选购指南";
            $how_to_buy['content']=$res['choose_html_text'];
            
            $faq['title'] = $classify_name."常见问题";
            $faq['content']=$res['faq_html_text'];
        }
        else
        {
            $how_to_buy['title'] = "";
            $how_to_buy['content']="";
            
            $faq['title'] = "";
            $faq['content']="";
        }
        
        
        
        
        $data['how_to_buy'] = $how_to_buy;
        $data['faq']=$faq;
        
        return $data;
    }
    
    
    //通过 易源 API 来获取数据
    private function get_info_product_yiyuan($barcode){
        //包名
        $pkg = 'com.mdkkj.zhongcetianxia';
        //appkey 
       $appkey = '71588de5d4c2b919a8fd432d39912317';
        //拼接聚合get请求链接
//        $url = 'http://api.juheapi.com/jhbar/bar?appkey='.$appkey.'&pkg='.$pkg.'&barcode='.$barcode.'&cityid=1';
        
        $timestamp = date("YmdHis",I("server.REQUEST_TIME"));
        
        $url = "http://route.showapi.com/66-22?code=$barcode&showapi_appid=12020&showapi_timestamp=$timestamp&showapi_sign=ff003a5c3fb3411c9ad3839365b5df49";
//        print_r($url);
        $list = file_get_contents($url);
//        print_r($list);
        //将list由返回的json格式转换为数组;
        $list = json_decode($list,true);
//        print_r($list);
        
        if($list['showapi_res_code']==0)
        {
            if(!empty($list['showapi_res_body']['goodsName']))
            {
                $data['name'] = $list['showapi_res_body']['goodsName'];
//            $data['pjname'] = $list['showapi_res_body']['goodsName'];
                $data['imgurl'] = $list['showapi_res_body']['img'];
                $data['barcode'] = $barcode;
                $data['ctime'] = I('server.REQUEST_TIME');

                $id = M('product')->data($data)->add();

                if(!empty($id)){

                    $res = M('product')->find($id);
                    $res['item_count']= 0;
                    $res['items']=array();

                }else{

                    return $this->get_info_product_yiyuan_twice($barcode);
                }

                return $res;
            }
            else
            {
                return false;
            }
            
            
        }
        else
        {
            return $this->get_info_product_yiyuan_twice($barcode);
        }
    }
    
    private function get_info_product_yiyuan_twice($barcode){
        //包名
        $pkg = 'com.mdkkj.zhongcetianxia';
        //appkey 
       $appkey = '71588de5d4c2b919a8fd432d39912317';
        //拼接聚合get请求链接
//        $url = 'http://api.juheapi.com/jhbar/bar?appkey='.$appkey.'&pkg='.$pkg.'&barcode='.$barcode.'&cityid=1';
        
        $timestamp = date("YmdHis",I("server.REQUEST_TIME"));
        
        $url = "http://route.showapi.com/66-22?code=$barcode&showapi_appid=12020&showapi_timestamp=$timestamp&showapi_sign=ff003a5c3fb3411c9ad3839365b5df49";
//        print_r($url);
        $list = file_get_contents($url);
//        print_r($list);
        //将list由返回的json格式转换为数组;
        $list = json_decode($list,true);
//        print_r($list);
        
        if($list['showapi_res_code']==0)
        {
            if(!empty($list['showapi_res_body']['goodsName']))
            {
                
                $data['name'] = $list['showapi_res_body']['goodsName'];
//            $data['pjname'] = $list['showapi_res_body']['goodsName'];
                $data['imgurl'] = $list['showapi_res_body']['img'];
                $data['barcode'] = $barcode;
                $data['ctime'] = I('server.REQUEST_TIME');

                $id = M('product')->data($data)->add();

                if(!empty($id)){

                    $res = M('product')->find($id);
                    $res['item_count']= 0;
                    $res['items']=array();

                }else{

                    return false;
                }

                return $res;
            }
            else
            {
                return false;
            }
            
        }
        else
        {
            return false;
        }
    }
    
    
    /*
     * 统一输出的格式
     */
    public function json_output($data,$suc_msg="OK",$err_msg="NO",$more_data) {
        if(!empty($data))
        {
            $res['err']=0;
            $res['msg']=$suc_msg;
            $res['count']=count($data);

            $res['content']=$data;
            
            
            
        }
        else
        {
            $res['err']=0;
            $res['msg']=$err_msg;
            $res['count']=0;
            $res['content']="";
        }
        if(!empty($more_data))
        {
            $res['more_data']=$more_data;
        }
        
        echo json_encode($res);
    }
    
}

    